package com.lkz.shiro;

import com.lkz.entity.Employee;
import com.lkz.entity.Permission;
import com.lkz.entity.Role;
import com.lkz.service.IEmployeeService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


public class MyRealm extends AuthorizingRealm {
    @Autowired
    private IEmployeeService employeeService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
        for (Role role : employee.getRoleList()) {
            info.addRole(role.getRoleName());
            for (Permission permission : role.getPermissions()) {
                info.addStringPermission(permission.getPermission());
            }
        }
        return info;
    }

    @Override
    protected SimpleAuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String empName = (String) authenticationToken.getPrincipal();
        Employee employee = employeeService.selectByName(empName);
        if(employee==null){
            throw new UnknownAccountException("该用户不存在");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(employee, employee.getPwd(), ByteSource.Util.bytes(employee.getCredentialsSalt()), getName());
        return info;
    }
}